#include "secureapimanager.h"
#include "configmanager.h"
#include "securetokenmanager.h"
#include <QJsonParseError>
#include <QStandardPaths>
#include <QDir>
#include <QEventLoop>
#include <QTimer>

// 静态成员初始化
SecureApiManager* SecureApiManager::s_instance = nullptr;
const QString SecureApiManager::USER_AGENT = QString("LimeReader/%1 SecureAPI/1.0").arg(LimeReader::AppVersion::getAppVersion());
const QString SecureApiManager::API_VERSION = "v1";

SecureApiManager::SecureApiManager(QObject *parent)
    : QObject(parent)
    , m_networkManager(new QNetworkAccessManager(this))
    , m_heartbeatTimer(new QTimer(this))
    , m_healthCheckTimer(new QTimer(this))
    , m_currentEndpointIndex(0)
    , m_endpointRotationEnabled(true)
    , m_maxRetryAttempts(DEFAULT_RETRY_ATTEMPTS)
    , m_requestTimeout(DEFAULT_REQUEST_TIMEOUT)
    , m_requestSigningEnabled(true)
    , m_heartbeatInterval(DEFAULT_HEARTBEAT_INTERVAL)
    , m_heartbeatActive(false)
{

    // 连接定时器
    connect(m_heartbeatTimer, &QTimer::timeout, this, &SecureApiManager::onHeartbeatTimer);
    connect(m_healthCheckTimer, &QTimer::timeout, this, &SecureApiManager::performHealthCheck);

    // 初始化默认端点
    initializeDefaultEndpoints();

    // 加载认证Token
    m_authToken = ConfigManager::getAuthToken();

    // 选择初始端点
    m_currentEndpoint = selectBestEndpoint();

    // 启动健康检查（每2分钟检查一次）
    m_healthCheckTimer->start(2 * 60 * 1000);

}

SecureApiManager::~SecureApiManager()
{
    stopHeartbeat();
}

SecureApiManager& SecureApiManager::instance()
{
    if (!s_instance) {
        s_instance = new SecureApiManager();
    }
    return *s_instance;
}

void SecureApiManager::initializeDefaultEndpoints()
{

    // 尝试从主配置文件加载端点配置
    loadEndpointsFromConfig();

    // 如果配置文件中没有端点，使用默认配置
    if (m_endpoints.isEmpty()) {

        // 添加主端点
        addApiEndpoint("https://ctdy123.com/api", 100);

        // 添加备用端点
        addApiEndpoint("https://loimreader.com/api", 90);

    } else {
    }
}

void SecureApiManager::loadEndpointsFromConfig()
{

    ConfigManager::initialize();

    // 获取端点配置
    QJsonArray endpoints = ConfigManager::getNestedArray("apiEndpoints", "endpoints");
    if (endpoints.isEmpty()) {
        return;
    }

    for (const QJsonValue& endpointValue : endpoints) {
        QJsonObject endpointObj = endpointValue.toObject();

        QString url = endpointObj["url"].toString();
        int priority = endpointObj["priority"].toInt(50);
        QString status = endpointObj["status"].toString("active");

        // 只添加状态为active或standby的端点
        if (status == "active" || status == "standby") {
            addApiEndpoint(url, priority);
        } else {
        }
    }

    // 加载轮换策略配置
    QJsonObject rotationStrategy = ConfigManager::getNestedObject("apiEndpoints", "rotationStrategy");
    if (!rotationStrategy.isEmpty()) {
        m_endpointRotationEnabled = rotationStrategy["enabled"].toBool(true);
    }

    // 加载安全配置
    QJsonObject securityConfig = ConfigManager::getNestedObject("apiEndpoints", "security");
    if (!securityConfig.isEmpty()) {
        m_requestSigningEnabled = securityConfig["requestSigning"].toBool(true);
        m_maxRetryAttempts = securityConfig["maxRetryAttempts"].toInt(3);
        m_requestTimeout = securityConfig["requestTimeout"].toInt(30000);
    }
}

void SecureApiManager::addApiEndpoint(const QString& endpoint, int priority)
{
    if (endpoint.isEmpty() || !endpoint.startsWith("http")) {
        return;
    }

    EndpointInfo info;
    info.url = endpoint;
    info.priority = priority;
    info.isHealthy = true;
    info.consecutiveFailures = 0;
    info.totalSuccesses = 0;
    info.totalFailures = 0;

    m_endpoints[endpoint] = info;
}

void SecureApiManager::removeApiEndpoint(const QString& endpoint)
{
    if (m_endpoints.contains(endpoint)) {
        m_endpoints.remove(endpoint);

        // 如果移除的是当前端点，重新选择
        if (m_currentEndpoint == endpoint) {
            m_currentEndpoint = selectBestEndpoint();
        }
    }
}

QStringList SecureApiManager::getAvailableEndpoints() const
{
    QStringList endpoints;
    for (auto it = m_endpoints.begin(); it != m_endpoints.end(); ++it) {
        endpoints << it.value().url;
    }
    return endpoints;
}

QString SecureApiManager::getCurrentEndpoint() const
{
    return m_currentEndpoint;
}

void SecureApiManager::rotateEndpoint()
{
    QString oldEndpoint = m_currentEndpoint;
    m_currentEndpoint = selectBestEndpoint();

    if (m_currentEndpoint != oldEndpoint) {
        m_statistics.endpointRotations++;

        // emit endpointRotated(oldEndpoint, m_currentEndpoint);
    }
}

void SecureApiManager::markEndpointFailed(const QString& endpoint)
{
    if (!m_endpoints.contains(endpoint)) {
        return;
    }

    EndpointInfo& info = m_endpoints[endpoint];
    info.lastFailure = QDateTime::currentDateTime();
    info.consecutiveFailures++;
    info.totalFailures++;

    // 如果连续失败次数过多，标记为不健康
    if (info.consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) {
        info.isHealthy = false;
    }

    updateEndpointStatistics(endpoint, false);

    // 如果是当前端点失败，考虑轮换
    if (endpoint == m_currentEndpoint && m_endpointRotationEnabled) {
        scheduleEndpointRotation();
    }
}

void SecureApiManager::markEndpointSuccess(const QString& endpoint)
{
    if (!m_endpoints.contains(endpoint)) {
        return;
    }

    EndpointInfo& info = m_endpoints[endpoint];
    info.lastSuccess = QDateTime::currentDateTime();
    info.lastUsed = QDateTime::currentDateTime();
    info.consecutiveFailures = 0;
    info.totalSuccesses++;
    info.isHealthy = true;

    updateEndpointStatistics(endpoint, true);
}

void SecureApiManager::setAuthToken(const QString& token)
{
    m_authToken = token;

    // 同时保存到ConfigManager
    ConfigManager::setAuthToken(token);
}

QString SecureApiManager::getAuthToken() const
{
    return m_authToken;
}

bool SecureApiManager::hasValidToken() const
{
    return !m_authToken.isEmpty();
}

QNetworkReply* SecureApiManager::sendSecureRequest(const QString& endpoint,
                                                 const QJsonObject& data,
                                                 const QString& method,
                                                 bool autoRetry)
{
    QString actualEndpoint = endpoint.isEmpty() ? m_currentEndpoint : endpoint;


    // 构建安全请求
    QNetworkRequest request = buildSecureRequest(actualEndpoint, data, method);

    // 准备请求体
    QByteArray requestData;
    if (method.toUpper() != "GET") {
        QJsonObject payload = buildRequestPayload(data, method);
        QJsonDocument doc(payload);
        requestData = doc.toJson(QJsonDocument::Compact);
    }

    // 发送请求
    QNetworkReply* reply = nullptr;
    if (method.toUpper() == "GET") {
        reply = m_networkManager->get(request);
    } else if (method.toUpper() == "POST") {
        reply = m_networkManager->post(request, requestData);
    } else if (method.toUpper() == "PUT") {
        reply = m_networkManager->put(request, requestData);
    } else if (method.toUpper() == "DELETE") {
        reply = m_networkManager->deleteResource(request);
    }

    if (reply) {
        // 设置请求超时
        QTimer::singleShot(m_requestTimeout, reply, &QNetworkReply::abort);

        // 记录请求上下文
        RequestContext context;
        context.endpoint = actualEndpoint;
        context.data = data;
        context.method = method;
        context.attemptCount = 1;
        context.requestTime = QDateTime::currentDateTime();
        context.autoRetry = autoRetry;

        m_activeRequests[reply] = context;

        // 更新统计
        m_statistics.totalRequests++;
        m_statistics.lastRequestTime = QDateTime::currentDateTime();

        connect(reply, &QNetworkReply::finished, this, &SecureApiManager::onRequestFinished);

    }

    return reply;
}

void SecureApiManager::fetchUserProfile()
{
    QNetworkReply* reply = sendSecureRequest("/user/profile", QJsonObject(), "GET");
    connect(reply, &QNetworkReply::finished, this, [this, reply]() {
        onRequestFinished();
        // 处理用户信息响应
        if (reply->error() == QNetworkReply::NoError) {
            QByteArray responseData = reply->readAll();
            QJsonParseError error;
            QJsonDocument doc = QJsonDocument::fromJson(responseData, &error);

            if (error.error == QJsonParseError::NoError && doc.isObject()) {
                QJsonObject userProfile = doc.object();
                emit userProfileFetched(userProfile);
            } else {
                emit apiError("用户信息解析失败", error.errorString());
            }
        } else {
            handleRequestError(reply, "获取用户信息");
        }
        reply->deleteLater();
    });
}

void SecureApiManager::fetchUserSubscription()
{
    QNetworkReply* reply = sendSecureRequest("/user/subscription", QJsonObject(), "GET");
    connect(reply, &QNetworkReply::finished, this, [this, reply]() {
        onRequestFinished();
        // 处理订阅信息响应
        if (reply->error() == QNetworkReply::NoError) {
            QByteArray responseData = reply->readAll();
            QJsonParseError error;
            QJsonDocument doc = QJsonDocument::fromJson(responseData, &error);

            if (error.error == QJsonParseError::NoError && doc.isObject()) {
                QJsonObject subscription = doc.object();
                emit userSubscriptionFetched(subscription);
            } else {
                emit apiError("订阅信息解析失败", error.errorString());
            }
        } else {
            handleRequestError(reply, "获取订阅信息");
        }
        reply->deleteLater();
    });
}

void SecureApiManager::fetchDeviceList()
{
    QNetworkReply* reply = sendSecureRequest("/user/devices", QJsonObject(), "GET");
    connect(reply, &QNetworkReply::finished, this, [this, reply]() {
        onRequestFinished();
        // 处理设备列表响应
        if (reply->error() == QNetworkReply::NoError) {
            QByteArray responseData = reply->readAll();
            QJsonParseError error;
            QJsonDocument doc = QJsonDocument::fromJson(responseData, &error);

            if (error.error == QJsonParseError::NoError && doc.isObject()) {
                QJsonObject root = doc.object();
                if (root.contains("devices") && root["devices"].isArray()) {
                    QJsonArray devices = root["devices"].toArray();
                    emit deviceListFetched(devices);
                } else {
                    emit apiError("设备列表格式错误", "响应中缺少devices数组");
                }
            } else {
                emit apiError("设备列表解析失败", error.errorString());
            }
        } else {
            handleRequestError(reply, "获取设备列表");
        }
        reply->deleteLater();
    });
}

void SecureApiManager::sendHeartbeat()
{
    if (!hasValidToken()) {
        return;
    }

    QJsonObject heartbeatData;
    heartbeatData["timestamp"] = QDateTime::currentSecsSinceEpoch();
    heartbeatData["clientInfo"] = QJsonObject{
        {"version", LimeReader::AppVersion::getAppVersion()},
        {"platform", QSysInfo::productType()},
        {"arch", QSysInfo::currentCpuArchitecture()}
    };

    QNetworkReply* reply = sendSecureRequest("/auth/client/heartbeat", heartbeatData);
    connect(reply, &QNetworkReply::finished, this, [this, reply]() {
        onRequestFinished();
        // 处理心跳响应
        if (reply->error() == QNetworkReply::NoError) {
            QByteArray responseData = reply->readAll();
            QJsonParseError error;
            QJsonDocument doc = QJsonDocument::fromJson(responseData, &error);

            if (error.error == QJsonParseError::NoError && doc.isObject()) {
                QJsonObject response = doc.object();
                emit heartbeatSuccess();

                // 检查服务器响应中的版本信息
                if (response.contains("serverVersion")) {
                    QString serverVersion = response["serverVersion"].toString();
                    // 可以在这里进行版本检查
                }
            } else {
                emit heartbeatError("响应解析失败");
            }
        } else {
            handleRequestError(reply, "心跳");
            emit heartbeatError(reply->errorString());
        }
        reply->deleteLater();
    });
}

void SecureApiManager::kickDevice(const QString& sessionId)
{
    QJsonObject kickData;
    kickData["sessionId"] = sessionId;
    kickData["reason"] = "用户主动踢出";

    QNetworkReply* reply = sendSecureRequest("/sessions/kick", kickData);
    connect(reply, &QNetworkReply::finished, this, [this, reply, sessionId]() {
        onRequestFinished();
        // 处理踢出设备响应
        if (reply->error() == QNetworkReply::NoError) {
            QByteArray responseData = reply->readAll();
            QJsonParseError error;
            QJsonDocument doc = QJsonDocument::fromJson(responseData, &error);

            if (error.error == QJsonParseError::NoError && doc.isObject()) {
                QJsonObject response = doc.object();
                emit deviceKickSuccess(sessionId);
            } else {
                emit deviceKickError("响应解析失败");
            }
        } else {
            handleRequestError(reply, "踢出设备");
            emit deviceKickError(reply->errorString());
        }
        reply->deleteLater();
    });
}

void SecureApiManager::logout()
{
    QNetworkReply* reply = sendSecureRequest("/auth/logout", QJsonObject());
    connect(reply, &QNetworkReply::finished, this, [this, reply]() {
        onRequestFinished();
        // 无论登出请求是否成功，都清除本地认证信息
        QString token = m_authToken;
        m_authToken.clear();
        ConfigManager::setAuthToken("");
        ConfigManager::clearSecureToken();

        if (reply->error() == QNetworkReply::NoError) {
            emit logoutFinished(true);
        } else {
            emit logoutFinished(true); // 本地登出仍然成功
        }

        reply->deleteLater();
    });
}

void SecureApiManager::startHeartbeat()
{
    if (m_heartbeatActive) {
        return;
    }

    if (!hasValidToken()) {
        emit apiError("无法启动心跳", "缺少有效Token");
        return;
    }

    m_heartbeatActive = true;
    m_heartbeatTimer->start(m_heartbeatInterval);

    // 立即发送一次心跳
    sendHeartbeat();
}

void SecureApiManager::stopHeartbeat()
{
    if (!m_heartbeatActive) {
        return;
    }

    m_heartbeatActive = false;
    m_heartbeatTimer->stop();
}

bool SecureApiManager::isHeartbeatActive() const
{
    return m_heartbeatActive;
}

void SecureApiManager::setMaxRetryAttempts(int attempts)
{
    m_maxRetryAttempts = qMax(1, attempts);
}

void SecureApiManager::setRequestTimeout(int milliseconds)
{
    m_requestTimeout = qMax(1000, milliseconds);
}

void SecureApiManager::setEndpointRotationEnabled(bool enabled)
{
    m_endpointRotationEnabled = enabled;
}

void SecureApiManager::setRequestSigningEnabled(bool enabled)
{
    m_requestSigningEnabled = enabled;
}

SecureApiManager::ApiStats SecureApiManager::getStatistics() const
{
    return m_statistics;
}

void SecureApiManager::resetStatistics()
{
    m_statistics = ApiStats();
}

void SecureApiManager::performHealthCheck()
{

    QStringList endpoints = getAvailableEndpoints();
    for (const QString& endpoint : endpoints) {
        if (!isEndpointHealthy(endpoint)) {
            continue; // 跳过已知不健康的端点
        }

        QNetworkRequest request(QUrl(endpoint + "/health"));
        request.setRawHeader("User-Agent", USER_AGENT.toUtf8());
        request.setRawHeader("Accept", "application/json");

        QNetworkReply* reply = m_networkManager->get(request);
        QTimer::singleShot(5000, reply, &QNetworkReply::abort); // 5秒超时

        connect(reply, &QNetworkReply::finished, this, [this, reply, endpoint]() {
            if (reply->error() == QNetworkReply::NoError) {
                markEndpointSuccess(endpoint);
            } else {
                markEndpointFailed(endpoint);
            }
            reply->deleteLater();
        });
    }
}

bool SecureApiManager::isEndpointHealthy(const QString& endpoint) const
{
    if (!m_endpoints.contains(endpoint)) {
        return false;
    }

    const EndpointInfo& info = m_endpoints[endpoint];

    // 检查是否连续失败过多
    if (info.consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) {
        return false;
    }

    // 检查是否在冷却期内
    if (info.lastFailure.isValid() &&
        info.lastFailure.msecsTo(QDateTime::currentDateTime()) < ENDPOINT_COOLDOWN_TIME) {
        return false;
    }

    return info.isHealthy;
}

QStringList SecureApiManager::getHealthyEndpoints() const
{
    QStringList healthyEndpoints;
    for (auto it = m_endpoints.begin(); it != m_endpoints.end(); ++it) {
        if (isEndpointHealthy(it.value().url)) {
            healthyEndpoints << it.value().url;
        }
    }
    return healthyEndpoints;
}

QString SecureApiManager::selectBestEndpoint()
{
    QStringList healthyEndpoints = getHealthyEndpoints();

    if (healthyEndpoints.isEmpty()) {
        if (!m_endpoints.isEmpty()) {
            return m_endpoints.begin().key();
        }
        return QString();
    }

    // 根据优先级和成功率选择最佳端点
    QString bestEndpoint = healthyEndpoints.first();
    double bestScore = calculateEndpointScore(bestEndpoint);

    for (const QString& endpoint : healthyEndpoints) {
        double score = calculateEndpointScore(endpoint);
        if (score > bestScore) {
            bestScore = score;
            bestEndpoint = endpoint;
        }
    }

    return bestEndpoint;
}

double SecureApiManager::calculateEndpointScore(const QString& endpoint) const
{
    if (!m_endpoints.contains(endpoint)) {
        return 0.0;
    }

    const EndpointInfo& info = m_endpoints[endpoint];

    // 基础分数 = 优先级
    double score = info.priority;

    // 成功率加成
    int totalRequests = info.totalSuccesses + info.totalFailures;
    if (totalRequests > 0) {
        double successRate = static_cast<double>(info.totalSuccesses) / totalRequests;
        score *= (0.5 + 0.5 * successRate); // 50%基础 + 50%成功率权重
    }

    // 最近成功时间加成
    if (info.lastSuccess.isValid()) {
        qint64 hoursSinceSuccess = info.lastSuccess.secsTo(QDateTime::currentDateTime()) / 3600;
        if (hoursSinceSuccess < 1) {
            score *= 1.2; // 最近1小时内成功，加分20%
        } else if (hoursSinceSuccess < 24) {
            score *= 1.1; // 最近24小时内成功，加分10%
        }
    }

    return score;
}

void SecureApiManager::updateEndpointStatistics(const QString& endpoint, bool success)
{
    if (success) {
        m_statistics.successfulRequests++;
        m_statistics.lastSuccessTime = QDateTime::currentDateTime();
        m_statistics.endpointSuccessCount[endpoint]++;
    } else {
        m_statistics.failedRequests++;
        m_statistics.lastFailureTime = QDateTime::currentDateTime();
        m_statistics.endpointFailureCount[endpoint]++;
    }
}

QNetworkRequest SecureApiManager::buildSecureRequest(const QString& endpoint, const QJsonObject& data, const QString& method)
{
    QUrl url(endpoint);
    if (!url.isValid()) {
        return QNetworkRequest();
    }

    QNetworkRequest request(url);

    // 设置基本头部
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setHeader(QNetworkRequest::UserAgentHeader, USER_AGENT);
    request.setRawHeader("Accept", "application/json");
    request.setRawHeader("X-API-Version", API_VERSION.toUtf8());
    request.setRawHeader("X-Client-Version", LimeReader::AppVersion::getAppVersion().toUtf8());

    // 添加认证头部
    if (!m_authToken.isEmpty()) {
        request.setRawHeader("Authorization", QString("Bearer %1").arg(m_authToken).toUtf8());
    }

    // 添加请求签名
    if (m_requestSigningEnabled) {
        qint64 timestamp = QDateTime::currentMSecsSinceEpoch();
        QString nonce = generateNonce();
        QString signature = generateRequestSignature(endpoint, data, method, timestamp);

        request.setRawHeader("X-Timestamp", QString::number(timestamp).toUtf8());
        request.setRawHeader("X-Nonce", nonce.toUtf8());
        request.setRawHeader("X-Signature", signature.toUtf8());
    }

    // 添加设备指纹
    QString deviceFingerprint = generateDeviceFingerprint();
    request.setRawHeader("X-Device-Fingerprint", deviceFingerprint.toUtf8());

    return request;
}

QString SecureApiManager::generateRequestSignature(const QString& endpoint, const QJsonObject& data, const QString& method, qint64 timestamp)
{
    // 构建待签名字符串
    QStringList signParts;
    signParts << method.toUpper();
    signParts << endpoint;
    signParts << QString::number(timestamp);

    if (!data.isEmpty()) {
        QJsonDocument doc(data);
        signParts << doc.toJson(QJsonDocument::Compact);
    }

    QString signString = signParts.join("|");

    // 使用HMAC-SHA256生成签名
    QByteArray key = m_authToken.toUtf8(); // 使用Token作为密钥
    QByteArray message = signString.toUtf8();

    QByteArray hmac = QCryptographicHash::hash(message + key, QCryptographicHash::Sha256);
    return hmac.toHex();
}

QString SecureApiManager::generateNonce()
{
    QByteArray nonce(16, 0);
    QRandomGenerator* rng = QRandomGenerator::global();
    for (int i = 0; i < 16; ++i) {
        nonce[i] = static_cast<char>(rng->bounded(256));
    }
    return nonce.toBase64(QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals);
}

QJsonObject SecureApiManager::buildRequestPayload(const QJsonObject& data, const QString& method)
{
    QJsonObject payload = data;

    // 添加通用字段
    payload["timestamp"] = QDateTime::currentSecsSinceEpoch();
    payload["method"] = method.toUpper();
    payload["apiVersion"] = API_VERSION;

    // 添加客户端信息
    QJsonObject clientInfo;
    clientInfo["version"] = LimeReader::AppVersion::getAppVersion();
    clientInfo["platform"] = QSysInfo::productType();
    clientInfo["arch"] = QSysInfo::currentCpuArchitecture();
    clientInfo["userAgent"] = USER_AGENT;
    payload["clientInfo"] = clientInfo;

    return payload;
}

QString SecureApiManager::generateDeviceFingerprint()
{
    // 使用SecureTokenManager的硬件指纹
    SecureTokenManager& tokenManager = SecureTokenManager::instance();
    return tokenManager.getHardwareFingerprint();
}

void SecureApiManager::handleRequestError(QNetworkReply* reply, const QString& context)
{
    QString errorString = reply->errorString();
    int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();


    // 标记端点失败
    QString endpoint = reply->url().toString();
    markEndpointFailed(endpoint);

    // 特殊错误处理
    if (statusCode == 401) {
        // Token过期或无效
        emit tokenExpired();
    } else if (statusCode == 403) {
        // 权限不足或设备被禁用
        emit deviceNotFound();
    } else if (statusCode >= 500) {
        // 服务器错误，考虑端点轮换
        if (m_endpointRotationEnabled) {
            scheduleEndpointRotation();
        }
    }

    emit apiError(context, errorString);
}

void SecureApiManager::scheduleEndpointRotation()
{
    // 延迟轮换，避免频繁切换
    QTimer::singleShot(1000, this, [this]() {
        rotateEndpoint();
    });
}

void SecureApiManager::onRequestFinished()
{
    QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
    if (!reply) {
        return;
    }

    if (!m_activeRequests.contains(reply)) {
        reply->deleteLater();
        return;
    }

    RequestContext context = m_activeRequests.value(reply);
    m_activeRequests.remove(reply);

    if (reply->error() == QNetworkReply::NoError) {
        markEndpointSuccess(context.endpoint);
    } else {
        markEndpointFailed(context.endpoint);

        // 自动重试逻辑
        if (context.autoRetry && context.attemptCount < m_maxRetryAttempts) {

            // 延迟重试
            int delayMs = 1000 * (1 << context.attemptCount); // 指数退避
            QTimer::singleShot(delayMs, this, [this, context]() {
                RequestContext retryContext = context;
                retryContext.attemptCount++;

                sendSecureRequest(retryContext.endpoint, retryContext.data, retryContext.method, false);
            });
        }
    }
}

void SecureApiManager::onHeartbeatTimer()
{
    if (m_heartbeatActive) {
        sendHeartbeat();
    }
}

void SecureApiManager::onHealthCheckFinished()
{
    // 健康检查完成
}

// EndpointConfigManager 实现
EndpointConfigManager* EndpointConfigManager::s_instance = nullptr;

EndpointConfigManager& EndpointConfigManager::instance()
{
    if (!s_instance) {
        s_instance = new EndpointConfigManager();
    }
    return *s_instance;
}

EndpointConfigManager::EndpointConfigManager()
    : m_currentRotationIndex(0)
{
    loadConfiguration();
}

EndpointConfigManager::~EndpointConfigManager()
{
    saveConfiguration();
}

void EndpointConfigManager::loadConfiguration()
{
    // 从配置文件或默认配置加载端点
}

void EndpointConfigManager::saveConfiguration()
{
    // 保存端点配置到文件
}

QJsonObject ApiEndpointConfig::toJson() const
{
    QJsonObject json;
    json["url"] = url;
    json["priority"] = priority;
    json["region"] = region;
    json["protocol"] = protocol;
    json["timeout"] = timeout;
    json["requiresAuth"] = requiresAuth;

    QJsonArray methodsArray;
    for (const QString& method : supportedMethods) {
        methodsArray.append(method);
    }
    json["supportedMethods"] = methodsArray;

    return json;
}

ApiEndpointConfig ApiEndpointConfig::fromJson(const QJsonObject& json)
{
    ApiEndpointConfig config;
    config.url = json["url"].toString();
    config.priority = json["priority"].toInt();
    config.region = json["region"].toString();
    config.protocol = json["protocol"].toString();
    config.timeout = json["timeout"].toInt();
    config.requiresAuth = json["requiresAuth"].toBool();

    if (json.contains("supportedMethods") && json["supportedMethods"].isArray()) {
        QJsonArray methodsArray = json["supportedMethods"].toArray();
        for (const QJsonValue& value : methodsArray) {
            config.supportedMethods.append(value.toString());
        }
    }

    return config;
}

